package com.example.lightenergypolymerize.config;

import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * springsecurity的配置
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Resource
    private LoginAuthenticationFilter loginAuthenticationFilter;
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        return http.httpBasic(AbstractHttpConfigurer::disable)//禁用明文验证
                .csrf(AbstractHttpConfigurer::disable)//禁用csrf验证
                .formLogin(AbstractHttpConfigurer::disable)//禁用默认登录页
                .logout(AbstractHttpConfigurer::disable)//禁用默认注销页
                .headers(AbstractHttpConfigurer::disable) // 禁用默认 Header（支持 iframe 访问页面）
                .sessionManagement(session -> //禁用session
                        session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers(//可以访问的资源
                                "/layui/**",
                                "/js/**",
                                "/css/**",
                                "login.html",
                                "index.html",
                                "register.html",
                                "/user/login",
                                "user/register",
                                "/captcha/create",
                                "/swagger-ui/**",//swagger
                                "/v3/**",//swagger
                                "/doc.html",//knife4j
                                "/webjars/**"//knife4j

                        ).permitAll()
                        .anyRequest().authenticated()//其他资源都需要认证
                )
                //添加自定义登录认证过滤器
                .addFilterBefore(loginAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
                .build();
    }
}
